package com.html2rss.core.parser;

import org.htmlparser.util.ParserException;
import org.htmlparser.util.NodeList;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.*;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.visitors.NodeVisitor;
import org.htmlparser.tags.*;

import java.io.*;


/**
 * User: vvs
 * Date: 31.03.2007
 * Time: 13:23:33
 */
public class HtmlToRss {
    public static void main(String[] args) throws ParserException, IOException {
        Parser parser = new Parser();
        parser.setResource("example1.html");
        parser.setFeedback(Parser.DEVNULL);

        NodeList list = null;
        TagNameFilter tagNameFilter = new TagNameFilter("title");
        list = parser.parse(null);
        NodeList newlist = list.extractAllNodesThatMatch(
                new OrFilter(
                        new NodeFilter[]{
                                new NodeClassFilter(ParagraphTag.class),
                                new NodeClassFilter(LinkTag.class),
                                new NodeClassFilter(TableColumn.class)
                        }
                ), true
        );
        newlist.visitAllNodesWith(new NodeVisitor() {
            public void visitTag(Tag tag) {
                tag.setAttribute("onclick", "javascript:select(this); return false;");
            }
        });

        Tag div = new Div();
        Parser addon = new Parser();
        addon.setInputHTML(readFile("scriptcode.js"));

        TagNode tagNode = new TagNode();
        tagNode.setTagName("/DIV");
        div.setEndTag(tagNode);
        list.add(addon.parse(null));

        FileWriter fw = new FileWriter("out.html");
        fw.write(list.toHtml());
        fw.close();
    }

    public static String readFile(String filename) {
        RandomAccessFile raf;
        byte[] bytes = null;
        try {
            raf = new RandomAccessFile(filename, "r");
            bytes = new byte[(int) raf.length()];
            raf.readFully(bytes);
            raf.close();
        } catch (IOException e) {
        }
        String result = new String(bytes);
        return result;
    }
}
